package example.rss;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import rlm.RuleLayoutManager;
import alm.ALMException;

public class RSSReader extends JFrame {

	private RuleLayoutManager rlm;
	private RSSManager manager;

	public RSSReader() throws ALMException {
		super("RSS Reader");
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);

		gatherFeeds();
		initLayout();
	}

	public void gatherFeeds() {
		manager = new RSSManager();
	}

	private void initLayout() throws ALMException {
		rlm = new RuleLayoutManager("layouts/rss.drl");
		this.setLayout(rlm);
		rlm.autoUpdate(true);

		JPanel feedsPanel = new JPanel();
		feedsPanel.setName("feeds");

		JPanel entriesPanel = new JPanel();
		entriesPanel.setName("entries");

		this.add(feedsPanel);
		this.add(entriesPanel);

		LabelCreator obj = new LabelCreator();
		rlm.addGlobal("creator", obj);
		
		JPanel innerPanel = new JPanel();
		innerPanel.setLayout(new BoxLayout(innerPanel, 1));
		innerPanel.setBackground(Color.white);
		innerPanel.setBorder(null);
		JScrollPane scroll = new JScrollPane(innerPanel);
		entriesPanel.setLayout(new BorderLayout());
		entriesPanel.add(scroll, BorderLayout.CENTER);
		scroll.setBorder(null);
		
		
		for (RSSFeed feed : manager.getFeeds()) {
			rlm.addFact(feed);
			rlm.addFact(feed.getEntries());
			for (RSSEntry entry : feed.getEntries()) {
				JLabel label = obj.entry(entry, 400, 90);
				JPanel panel = new JPanel();
				panel.add(label);
				panel.setBorder(BorderFactory.createLineBorder(Color.blue));
				panel.setBackground(Color.white);
				panel.setPreferredSize(new Dimension(400, 100));
				label.setLocation(0, 0);
				label.setPreferredSize(new Dimension(400, 90));
				innerPanel.add(panel);
			}
		}

	}

	public static void main(String[] args) throws ALMException {
		RSSReader reader = new RSSReader();
		reader.setLocation(400, 200);
		reader.setSize(400, 400);
		reader.setVisible(true);
		System.out.println("yes");
	}
}
